﻿using LdtDataEngin.ModuleDetail.PersonnelAnalysis.PersonnelModel.Personnel;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.LogicblockServers;
using LdtJudge.DataEngine.Model.Personnel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.PersonnelAnalysis.PersonnelModel
{
    public class PersonRegexSimple
    {
        /// <summary>
        /// 人员规则提取配置
        /// </summary>
        public string XmlConfig { get; set; }

        public string config { get; set; }
        public DataContext dataContext { get; set; }
        public string MatchParameterStr = "Prosecutor=2,89,164;Accused=1,90;Defender=168,169,13,99,100,101,102,103;Proxy=170,171,172,173,178,180;ProseProxy=2,89,164;AccusedProxy=1,90;Judger=t1,t2,t5,t4,t9;clerk=t6;";
        /// <summary>
        /// 提取人员信息
        /// </summary>
        public void Extract()
        {
            #region 人员信息添加
            List<CaseEntityInfoModel> caseEntityInfoModelList = new List<CaseEntityInfoModel>();
            CaseEntityInfoModel caseEntityInfoModel = new CaseEntityInfoModel();
            #endregion

            #region 对应人员信息
            //获取案件中人员基础信息
            var personCaseTypeInfo = this.GetPersonInfos(dataContext.DataLayerAns.CaseType, dataContext.DataLayerAns.SourceCode);
            List<An_anjianshiti> an_AnjianshitisList = new List<An_anjianshiti>();
            if (personCaseTypeInfo != null)
            {
                Dictionary<string, string> personInfos = new Dictionary<string, string>();
                string textformater = @"(?<=[^。\.；：])(?<!号|诉书|检察院|此致|(?<=此致[^\r]*\r[^\r]*)法院|附：|(?:检察员|核对无)[^\r\n]+|诉状)\r\n";
                foreach (var parInfo in personCaseTypeInfo.Paragraphinfo)
                {
                    string contents = "";
                    List<string> paragraphCodeList = new List<string>();
                    if (!string.IsNullOrWhiteSpace(parInfo.Paragraphcode))
                    {
                        string paragraphcode = parInfo.Paragraphcode.ToLower();
                        paragraphCodeList = paragraphcode.Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();
                    }
                    List<An_duanluo> sD_ParagraphTXTList = dataContext.DataLayerAns.Duanluos.Where(a => paragraphCodeList.Contains(a.Duanluobianhao.ToLower())).ToList();
                    if (sD_ParagraphTXTList != null)
                    {
                        foreach (An_duanluo SD_ParagraphModel in sD_ParagraphTXTList)
                        {
                            string value = SD_ParagraphModel.Duanluoneirong;
                            if (string.IsNullOrEmpty(contents))
                            {
                                contents = value;
                            }
                            else
                            {
                                contents = contents + "\r\n" + value;
                            }
                        }
                    }
                    contents = new Regex(textformater).Replace(contents, "");

                    List<string> SentenceItems = new List<string>();
                    if (parInfo.Splitsentence != null)
                    {
                        //进行拆分句子；
                        string ruid = Ldt.DataEngine.RuleAssemble.RuleParseClass.GetRIU_ID(parInfo.Splitsentence.Regexcode);
                        var sentenceItems = Ldt.DataEngine.RuleAssemble.RuleParseClass.GetParseList(ruid, contents);
                        SentenceItems.AddRange(sentenceItems);
                    }
                    else
                    {
                        //整个段落内容
                        SentenceItems.Add(contents);
                    }
                  
                    foreach (var item in SentenceItems)
                    {
                        string suitName = Ldt.DataEngine.RuleAssemble.RuleParseClass.GetParseValue(parInfo.Getnameinfo.RegexCode, item);
                        string suitDegree = Ldt.DataEngine.RuleAssemble.RuleParseClass.GetParseValue(parInfo.Getsuitdrgree.RegexCode, item);
                        string getsex = "";
                        string getAttendState = "1";
                        if (parInfo.sex!=null && !string.IsNullOrEmpty(parInfo.sex.RegexCode))
                        {
                            getsex = Ldt.DataEngine.RuleAssemble.RuleParseClass.GetParseValue(parInfo.sex.RegexCode, item);
                        }

                        if(parInfo.attendstate!=null && !string.IsNullOrWhiteSpace(parInfo.attendstate.RegexCode))
                        {
                            var attendDic= Ldt.DataEngine.RuleAssemble.RuleParseClass.GetParseValueDic(parInfo.attendstate.RegexCode,item);
                            if(attendDic!=null)
                            {
                                string attendValue = string.Empty;
                                if (attendDic.ContainsKey("Ai"))
                                    attendValue = attendDic["Ai"][0];
                                else if (attendDic.ContainsKey("reg"))
                                    attendValue = attendDic["reg"][0];
                                if (!string.IsNullOrWhiteSpace(attendValue) && attendValue.Contains("未到庭"))
                                    getAttendState = "0";
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(suitName))
                        {
                            personInfos[suitName] = suitDegree;
                            An_anjianshiti anjianshiti = new An_anjianshiti();
                            anjianshiti.Bieming = suitDegree;
                            anjianshiti.Mingcheng = suitName;
                            anjianshiti.Xingbie = getsex;
                            if (parInfo.sex != null && !string.IsNullOrEmpty(parInfo.sex.RegexCode))
                            {
                                anjianshiti.Anjianshitiid =parInfo.sex.Defaultid;
                            }
                            anjianshiti.Chutingqk = getAttendState;
                            anjianshiti.Dizhi = parInfo.Dictionariescode;
                            an_AnjianshitisList.Add(anjianshiti);
                        }
                    }
                }
                //将当前提取获取到的人员信息，放入到参数集中。
                this.PersonnelFill(an_AnjianshitisList);
                PersonnelBaseClass personnelBaseClass = new PersonnelBaseClass(dataContext) { xmlconfig = config };
                personnelBaseClass.Loade();
            }
            #endregion
        }
        /// <summary>
        /// 填充人员实体内容
        /// </summary>
        /// <param name="entityResultsList"></param>
        private void PersonnelFill(List<An_anjianshiti> an_AnjianshitisList)
        {
            string caseetiyinfoid = "";
            string caseAngerid = "";
            foreach (var entity in an_AnjianshitisList)
            {
                //人员基础信息
                An_anjianshiti anjianshiti = new An_anjianshiti();
                anjianshiti.Anjianshitiid = Snowflake.Instance().GetId().ToString();
                anjianshiti.Mingcheng = entity.Mingcheng;
                anjianshiti.Chutingqk = entity.Chutingqk;
                if (!string.IsNullOrEmpty(entity.Xingbie))
                {
                    anjianshiti.Xingbie = DictionariesConver.DictionaryValue(entity.Xingbie, entity.Anjianshitiid);
                }
                An_anjianshitijuese juese = new An_anjianshitijuese();
                juese.Anjianshitiid = anjianshiti.Anjianshitiid;
                juese.Jueseid = Snowflake.Instance().GetId().ToString();
                juese.Juesesusongdiwei = DictionariesConver.DictionaryValue(entity.Bieming,entity.Dizhi);
                juese.SusongDiwei = entity.Bieming;
                juese.Juesemingcheng = GetArgumentValueByMatchWords(MatchParameterStr, juese.Juesesusongdiwei);
                if (juese.Juesesusongdiwei == "90" || juese.Juesesusongdiwei == "89"
                    || juese.Juesesusongdiwei == "1" || juese.Juesesusongdiwei == "7" ||
                    juese.Juesesusongdiwei == "13" || juese.Juesesusongdiwei == "155" ||
                    juese.Juesesusongdiwei == "156" || juese.Juesesusongdiwei == "157" ||
                    juese.Juesesusongdiwei == "19" || juese.Juesesusongdiwei == "29"
                    )
                {
                    caseetiyinfoid = juese.Juesesusongdiwei;
                    caseAngerid = anjianshiti.Anjianshitiid;
                    juese.Zhuzhangfangleixing = "";
                    juese.Juesexuhao = PersonnelReadIndex(juese.Juesesusongdiwei,true);
                }
                else
                {
                    juese.Zhuzhangfangleixing = caseetiyinfoid;
                    juese.Zhuzhangfangjihe = caseAngerid;
                    juese.Juesexuhao = PersonnelReadIndex(juese.Juesesusongdiwei, false);

                }
                
                // 对角色的当事人类型赋值
                if (dataContext.DataLayerAns.Anjianshitis == null)
                {
                    dataContext.DataLayerAns.Anjianshitis = new List<An_anjianshiti>();
                }
                if (anjianshiti.Anjianshitijueses == null)
                {
                    anjianshiti.Anjianshitijueses = new List<An_anjianshitijuese>();
                }
                anjianshiti.Anjianshitijueses.Add(juese);
                if (dataContext.DataLayerAns.Anjianshitijueses == null)
                {
                    dataContext.DataLayerAns.Anjianshitijueses = new List<An_anjianshitijuese>();
                }
                dataContext.DataLayerAns.Anjianshitijueses.Add(juese);
                if (dataContext.DataLayerAns.Anjianshitis?.FirstOrDefault(a => a.Mingcheng == anjianshiti.Mingcheng) == null)
                {
                    dataContext.DataLayerAns.Anjianshitis.Add(anjianshiti);
                }
                else
                {
                   var anjianshitimodel= dataContext.DataLayerAns.Anjianshitis.FirstOrDefault(a => a.Mingcheng == anjianshiti.Mingcheng);
                    if (anjianshitimodel.Anjianshitijueses.Count>0)
                    {
                        if (anjianshitimodel.Anjianshitijueses.FirstOrDefault(a=> a.Juesesusongdiwei== juese.Juesesusongdiwei)==null)
                        {
                            dataContext.DataLayerAns.Anjianshitis.Add(anjianshiti);
                        }
                    }
                }


            }
        }

        /// <summary>
        /// 计算人员角色下标
        /// </summary>
        /// <param name="SuitDegreeID">诉讼地位</param>
        /// <param name="isParty">是否当事人</param>
        /// <returns></returns>
        private int PersonnelReadIndex(string SuitDegreeID,bool isParty)
        {
            int ReadIndex = 0;
            if (dataContext.DataLayerAns.Anjianshitis != null)
            {
                List<An_anjianshiti> caseEntityInfoList = new List<An_anjianshiti>();
                if (isParty)
                {
                    caseEntityInfoList = dataContext.DataLayerAns.Anjianshitis.Where(a =>  a.Anjianshitijueses.FirstOrDefault(b => b.Juesesusongdiwei == SuitDegreeID) != null).ToList();
                }
                else
                {
                    caseEntityInfoList = dataContext.DataLayerAns.Anjianshitis.Where(a => a.Chutingqk != "0" && a.Anjianshitijueses.FirstOrDefault(b => b.Juesesusongdiwei == SuitDegreeID) != null).ToList();
                }
                 
                ReadIndex = caseEntityInfoList.Count + 1;
            }
            if (ReadIndex==0)
            {
                ReadIndex = 1;
            }
            return ReadIndex;
        }
        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        private string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                string paternStr = "(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、]){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }
        /// <summary>
        /// 获取当前案件类型的信息集合
        /// </summary>
        /// <param name="caseType">案件类型</param>
        /// <param name="dossierCode">卷宗Code</param>
        /// <returns></returns>
        private Dossiergroup GetPersonInfos(string caseType, string dossierCode)
        {
            try
            {
                var modelperson = XmlSerializeHelper.DESerializer<Personregexsimple>(XmlConfig);
                return modelperson.Dossiergroup.FirstOrDefault(p => p.Casetype.ToLower() == caseType.ToLower() && p.Dossiercode.ToLower() == dossierCode.ToLower());
            }
            catch (Exception)
            {
                return null;

            }
        }

    }
}
